package musicbox;

import java.util.Observable;
import java.util.Observer;

import javax.sound.midi.Receiver;
import javax.sound.midi.ShortMessage;

import neuralmusic.brain.RTScheduler;
import neuralmusic.brain.module.Scheduler;

import static java.lang.System.*;

public class BeatAgent implements Observer {

	// BeatAgent(Context context){
	// this.context=context;
	// }
	private Scheduler sched;
	private Receiver recv;
	double tlast=0.0;
	double dt=0.0;
	private double fact;
	private double fact1;
	private double fact2;
	double uncert=1.0;
	private Metro metro;
	private double tNext;
	
	BeatAgent(Receiver recv,Scheduler sched,int chan) {
		this.recv=recv;
		this.sched =sched;
		fact=.1;
		fact1=.9;
		fact2=.1;
		metro=new Metro(recv,chan,sched,50.0);
		tNext=0.0;
	}

	@Override
	public void update(Observable src, Object mess) {

		ShortMessage shm = (ShortMessage) mess;
		int cmd = shm.getCommand();
		
		if (cmd != ShortMessage.NOTE_ON)return;
		int dat2 = shm.getData2();

		if ( dat2 == 0) {
			return;
		}
		
		int chn = shm.getChannel();
		int dat1 = shm.getData1();

		
		
		out.printf(String.format(" cmd: %3d chn: %3d  data: %3d  %3d \n", cmd,
				chn, dat1, dat2));

		
		double t=sched.getCurrentTimeInSecs();
		
		if (tlast != 0.0){
			double dt1=t-tlast;
			if (dt == 0.0) dt=dt1;
			else {		
				dt=dt*fact1+dt1*fact2;
			}
			tlast=t;
			tNext=t+dt;
			metro.adjust(tNext, dt);
		}  else {
			tlast=t;
		}
		
		
	}

	public void start() {
		metro.start();
		
	}
}
